# coding=utf-8

from fastapi import Depends, HTTPException, APIRouter
from sqlalchemy.orm import Session
from 学生管理系统.Dao import Scores_dao
from 学生管理系统.Datebase.Datebase import SessionLocal
from 学生管理系统.Query.Scores import Scores1  # 导入Pydantic模型
from 学生管理系统.Mondel.Scores_model import Scores  # 导入数据库模型

app02 = APIRouter()
# 依赖注入，每次调用接口都会进入这里实例化会话层
def get_db():
    db=SessionLocal()
    try:
        yield db
    finally:
        db.close()


@app02.get("/students/queryall", summary=["查询所有学生信息"])
def get_query(db: Session = Depends(get_db)):
    # 调用dao层sql语句接口
    return Scores_dao.get_query(db)


@app02.get("/students/{student_id}/queryid", summary=["用学生编号查询学生信息"])
def get_query(student_id: int, db: Session = Depends(get_db)):
    stu_info = Scores_dao.get_one_query(db, student_id)
    if stu_info is None:
        raise HTTPException(status_code=404,detail='该学生不存在')
    # 调用dao层sql语句接口
    return stu_info


# 根据学生编号student_id查询学生是否存在，不存在则添加的接口
@app02.post('/score/add/',summary=['添加学生成绩'])
def get_score_query(student_id:int,Scoress:Scores1,db:Session=Depends(get_db)):
    add_score = Scores_dao.get_one_query(db,student_id)
    if add_score :
        raise HTTPException(status_code=404, detail='该学生已存在')
    add_score1 = Scores_dao.get_add(db,Scoress)
    return add_score1

# 根据学生编号student_id查询学生是否存在，存在则修改接口
@app02.put('/score/{student_id}/update',summary=['修改学生成绩'])
def get_score_query(Scoress:Scores1,student_id:int,db:Session=Depends(get_db)):
    up_score = Scores_dao.get_one_query(db,student_id)
    if up_score is  None :
        raise HTTPException(status_code=404, detail='该学生不存在')
    return Scores_dao.get_update(db,student_id,Scoress)

# 根据学生编号student_id查询学生是否存在，存在则删除，返回删除记录条数接口
@app02.get('/score/{student_id}/delete',summary=['删除学生成绩'])
def get_score_query(student_id:int,db:Session=Depends(get_db)):
    del_stu = Scores_dao.get_one_query(db,student_id)
    if del_stu is None :
        raise HTTPException(status_code=404, detail='该学生不存在')
    return Scores_dao.get_delete(db,student_id)
